$().ready(function(){
    let page = {};
    function init(){
        address();
        getCommunityInfo();
        getShoppingcartList();
    }
    init();

    //地址
    function address(){
        var provinceTag = document.getElementById("province");
        for(var i=0; i<provinceList.length; i++){
            var province = provinceList[i];
            var provinceName = ''
            if(province.name  == '北京'||province.name  == '上海'||province.name  == '天津'||province.name  == '重庆'){
                provinceName = province.name + '市'
            }else{
                provinceName = province.name + '省'
            }
            provinceTag.add(new Option(provinceName,i));
        }
    }
    $('#province').on('change',function(){
        var province = $(this).find('option:selected').text()
        $("#city").empty();
        $('#city').append('<option value="-1">请选择</option>')
        $("#area").empty();
        $('#area').append('<option value="-1">请选择</option>')
        for(var i=0; i<provinceList.length; i++){
            if(provinceList[i].name == province.substring(0, province.length - 1)){
                if(provinceList[i].cityList){
                    for(var j in provinceList[i].cityList){
                        $('#city').append('<option value="'+j+'">'+provinceList[i].cityList[j].name+'</option>')
                    }
                }
            }
        }
    })
    $('#city').on('change',function(){
        var province = $('#province').find('option:selected').text()
        var city = $(this).find('option:selected').text()
        $("#area").empty();
        $('#area').append('<option value="-1">请选择</option>')
        for(var i=0; i<provinceList.length; i++){
            if(provinceList[i].name == province.substring(0, province.length - 1)){
                if(provinceList[i].cityList){
                    for(var j in provinceList[i].cityList){
                        if(provinceList[i].cityList[j].name == city){
                            if(provinceList[i].cityList[j].areaList){
                                for(var z in provinceList[i].cityList[j].areaList){
                                    $('#area').append('<option value="'+z+'">'+provinceList[i].cityList[j].areaList[z]+'</option>')
                                }
                            }
                        }
                    }
                }
            }
        }
    })
    //获取社区信息
    function getCommunityInfo(){
        getAsyncAjax(`${global.apiUrl}/Api/Alladmin/community_level`,res=>{
            console.log(res);
            page.fid = res.fid;
            page.userId = res.user_id;
        },{
            id:global.community_id
        })
    }
    //获取清单列表
    function getShoppingcartList(){
        getAjax(`${global.apiUrl}/get_user_als_product_buycar`,res=>{
            // console.log(res);
            let html = '';
            let countPrice = 0;
            let countNum = 0;
            page.list = res;
            if(res.length != 0){
                $('.submit_btn_box').css('display','flex');
                for(let i in res){
                    countNum += Number(res[i].num);
                    countPrice += Number(res[i].num*res[i].price);
                    html += `
                     <div class="order_item">
                           <div class="width_60 product_contet">
                               <img src="${res[i].head_img}" alt="">
                               <div class="order_product_title">${res[i].product_name}</div>
                           </div>
                           <div class="width_10 tac">￥${res[i].price}</div>
                           <div class="width_10 tac">${res[i].num}</div>
                           <div class="width_10 tac">￥${res[i].num*res[i].price}</div>
                           <div class="width_10 tac" style="color:#0d8ddb;cursor:pointer;">
                               <span data-id="${res[i].id}" class="del">移除</span>
                               <span data-id="${res[i].id}" class="reset" style="margin-left: 5px;" data-toggle="modal" data-target="#numModal">修改</span>
                           </div>
                       </div>
                `
                }
            }else{
                html = `
                    <div style="width: 100%;font-size: 16px;color:#aaa;text-align: center;line-height: 60px;">购物清单空空的哦~,请到产品列表添加产品吧！若已添加请关闭页面，重新进入！</div>
                `
                $('.submit_btn_box').css('display','none');

            }
            $('#count_num').text(countNum);
            $('#count_price').text(countPrice.toFixed(2));
            $('#shoppingcart_list').html(html);
        },{
            shop_id:page.fid,
            user_id:page.userId
        })
    }
    //操作购物车
    function  operationShoppingcart(type,num,price,id) {
        let text = '操作成功！';
        if(type == 2){
            if(num == 0){
                let cf = confirm('是否确认从订货清单中移除该产品？');
                if(cf){
                    text = '产品已移除清单'
                }else{
                    return;
                }
            }
        }
        if(type == 3){
            let cf = confirm('是否确认将所以产品移除订货清单？');
            if(cf){
                text = '订货清单已全部清空！';
            }else{
                return;
            }
        }
        getAjax(`${global.apiUrl}/operation_als_product_buycar`,res=>{
            console.log(res);
            if(res==1){
                alert(text);
                $('#numModal').modal('hide');
                getShoppingcartList();
            }
        },{
            type:type,//2减少数量为0 时自动删除   3清空购物车
            num:num,
            price:price,
            user_id:page.userId,
            id:id,
            community_shop_id:page.fid
        })
    }
    //删除产品
    $('#shoppingcart_list').on('click','.del',function(){
        let id = $(this).data('id');
        console.log(id);
        operationShoppingcart(2,0,0,id);
    })
    //清空购物车
    $('.clear_shoppingcart').on('click',function(){
        operationShoppingcart(3);
    })
    //modal 初始化
    $('#numModal').on('show.bs.modal',function(e){
        let modal = $(this);
        let btn = $(e.relatedTarget);
        let id = btn.data('id');
        modal.find('#shoppingcart_id').val(id);
        console.log(id);
        let info = {};
        for(let i in page.list){
            if(id == page.list[i].id){
                info = page.list[i];
            }
        }
        modal.find('#f_name').val(info.product_name);
        modal.find('#f_num').val(info.num);
        modal.find('#shoppingcart_price').val(info.price);
    })
    //修改数量
    $('#submit_foods_btn').on('click',function(){
        let num = $('#f_num').val();
        let id = $('#shoppingcart_id').val();
        let price = $('#shoppingcart_price').val()*num;
        operationShoppingcart(2,num,price,id);
    })
    //二维码生成
    let qrcode = new QRCode("qrcode");
    let timer = null;//声明定时器
    //判断订单状态
    function getOrderStatus(order_num){
        getAjax(`${global.apiUrl}/Api/Communityservicepay/get_order_status`,res=>{
            console.log(res);
            if(res.status == 1){
                clearInterval(timer);
                $('#payModal').modal('hide');
                alert('支付成功');

            }
        },{
            order_num:order_num
        })
    }
    //关闭支付窗口
    $('.close-pay-box').on('click',function(){
       clearInterval(timer);
       $('#payModal').modal('hide');
    });
    //结算
    $('#submit_address_btn').on('click',function(){
        let sheng = $('#province').children('option:selected').text();
        let shi = $('#city').children('option:selected').text();
        let qu = $('#area').children('option:selected').text();
        let address = $('#address').val();
        let name = $('#name').val();
        let phone = $('#phone').val();
        let date = new Date();
        let createtime = Math.round(date/1000);
        let closetime = createtime+60*60;
        if(!sheng||!shi||!qu||!address||!name||!phone){
            alert('请完善您的收货信息！');
            return;
        }
        $('#addressModal').modal('hide');
        $('#payModal').modal('show');
        let user_id = page.userId;
        let list = page.list;
        let all_product = [];
        let all_id = new Array();
        let all_price = 0;

        for(let i in list){
            all_id.push(list[i].id);
            let product = {
                product_id:list[i].product_id,
                price:list[i].num*list[i].price,
                num:list[i].num
            }
            all_price += Number(list[i].num*list[i].price);
            all_product.push(product);
        }
        let order_content = {
            sheng:sheng,
            shi:shi,
            qu:qu,
            address:address,
            phone:phone,
            name:name,
            all_price:all_price,
            community_shop_id: page.fid,
            buy_community_id:global.community_id,
            createtime:createtime,
            closetime:closetime
        }
        order_content = JSON.stringify(order_content);
        all_product = JSON.stringify(all_product);
        all_id = JSON.stringify(all_id);
        $.ajax({
            url:`${global.apiUrl}/Api/Communityservicepay/index`,
            dataType:'text',
            data:{
                user_id:user_id,
                order_content:order_content,
                all_product:all_product,
                all_id:all_id
            },
            success(res){
                res = JSON.parse(res);
                if(res){
                    qrcode.makeCode(res.img_url);//生成二维码
                    let order_num = res.out_trade_no;
                    getShoppingcartList();
                    timer = setInterval(function () {
                        getOrderStatus(order_num);
                    },2000);
                }

            }
        })
    })
})
